#include "src/fservice.h"
#include "log/log.h"
#include "src/beep.h"
#include "src/led.h"
#include <pthread.h>

#include <csignal>
#include <execinfo.h>
void print_stacktrace() {
    void *array[20];
    size_t size;
    char **strings;
    size_t i;

    size = backtrace(array, 20);
    strings = backtrace_symbols(array, size);

    fprintf(stderr, "Stack trace:\n");
    for (i = 0; i < size; i++) {
        fprintf(stderr, "%s\n", strings[i]);
    }

    free(strings);
}

void signal_handler(int sig) {
    fprintf(stderr, "Received signal %d\n", sig);
    print_stacktrace();

    // 恢复默认信号处理并重新触发信号
    signal(sig, SIG_DFL);
    raise(sig);
}

void setup_crash_handlers() {
    signal(SIGSEGV, signal_handler);
    signal(SIGABRT, signal_handler);
    signal(SIGFPE,  signal_handler);
    signal(SIGILL,  signal_handler);
    signal(SIGBUS,  signal_handler);
}
void  ledStatusChangeCallback( bool FLAG){
    LOG_INFO("LED STATUS : %s",FLAG== Led::LED_ON ? "LED_ON" : "LED_OFF");
}
int main() {
    setup_crash_handlers();
    pthread_t threads[2];
    int thread_ids[2] = {0, 1};
    initLog();
    auto beep = new Beep();
    auto led = new Led(ledStatusChangeCallback);
    beep->setBeep(Beep::BEEP_OFF);
    if(pthread_create(&threads[0], nullptr, &FService::startServer, &thread_ids[0]) != 0) {
        LOG_ERROR("pthread_create error");
    }
    while (true) {
        //led->setLed(led->getLed() == Led::LED_ON ? Led::LED_OFF : Led::LED_ON);
        //LOG_DEBUG("led status : %d:%d",status,led->getLed());
        usleep(5E6); // 1000 微秒 = 1 毫秒
    }
    endLog();
    pthread_join(threads[0], nullptr);
    return 0;
}
